package com.znsd.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.znsd.entitys.Users;
import com.znsd.stu.service.UserService;

public class UserRealm extends AuthorizingRealm {
	@Autowired
	private UserService userService;
	// 认证：登录操作，并没有授权，只是做了一个验证而已。
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// ①、把AuthenticationToken转换为UsernamePasswordToken。
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		// ②、从UsernamePasswordToken中获取username
		String username = upToken.getUsername();
		Session session = SecurityUtils.getSubject().getSession();
		// ③、调用数据库的方法，从数据库中查询username对应的记录。
		Users user = userService.checkUsername(username,null);
		// ④、若用户不存在，则可以跑出UnknownAccountException异常。
		if (user == null) {
			throw new UnknownAccountException("用户不存在.");
		}
		// ⑤、根据用户信息的情况，决定是否需要抛出其它AuthenticationException异常。
		if (user.getUser_state()==1) {
			throw new LockedAccountException("用户被禁用");
		}
		// 生成加密的盐值
		ByteSource salt = ByteSource.Util.bytes(user.getUser_username());

		// ⑥、根据用户的情况，来构建AuthenticationInfo对象并返回。
		AuthenticationInfo info = new SimpleAuthenticationInfo(user.getUser_username(), user.getUser_password(), salt,
				this.getName());
		session.setAttribute("user", user);		
		return info;
	}
	//授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		// TODO Auto-generated method stub
		return null;
	}

}
